package com.itcoon.cloud.framework.i18n;

import com.itcoon.cloud.framework.utils.SpringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;

import java.util.Locale;
import java.util.Map;

public class I18ns {

    private static final Logger log = LoggerFactory.getLogger(I18ns.class);
    private static Map<String, MessageSource> messageSourceMap = SpringUtils.getBeansMap(MessageSource.class);

    private final MessageSource messageSource;

    public static I18ns getInstance(String registerName){
        return new I18ns(registerName);
    }

    private I18ns(String registerName){
        this.messageSource = messageSourceMap.get(registerName);
    }


    public String getMessage(String code){
        return getMessage(code, null, LocaleContextHolder.getLocale(), false);
    }

    public String getMessage(String code, String defaultMessage){
        return getMessage(code, defaultMessage, LocaleContextHolder.getLocale(), false);
    }

    public String getMessage(String code, String defaultMessage, Locale locale){
        return getMessage(code, defaultMessage, locale, false);
    }

    public String getMessage(String code, Locale locale){
        return getMessage(code, null, locale, false);
    }


    public String getMessage(String code, String defaultMessage, Locale locale,boolean includeVal, String... args){
        if(includeVal){
            for (int i = 0; i < args.length; i++) {
                args[i] = getMessage(args[i]);
            }
        }
        return messageSource == null ? defaultMessage : messageSource.getMessage(code, args, defaultMessage, locale);
    }

    public MessageSource getMessageSource() {
        return this.messageSource;
    }

}
